<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useMainStore } from "@/stores";
import { storeToRefs } from "pinia";
import { message, type FormInstance } from "ant-design-vue";
import {
  titleOption,
  availableOption,
  SKUOption,
  stockOption,
  cutOption,
  priceOption,
} from "@/utils/constant";
import _ from "lodash";
import api from "@/api";


const stores = useMainStore();
const { category_list } = storeToRefs(stores);

const isOpen = defineModel("open", {
  type: Boolean,
});
const tpId = defineModel("id", {
  type: [Number, null],
});

const emits = defineEmits<{
  (e: "saveTemplate"): void;
  (e: "close"): void;
}>();

const setIsOpen = (value: boolean) => {
  isOpen.value = value;
};

const onClose = () => {
  setIsOpen(false);
};

const returnPolicy_list = [
  { cid: '0', name: '不支持7天无理由退货' },
  { cid: '1', name: '支持7天无理由退货' },
  { cid: '2', name: '拆封后不支持7天无理由退货' }
]

const formRef = ref<FormInstance>();
const formState = reactive<any>({
  id: null,
  templateName: "", // 模板名称
  categoryId: null, // 类目id
  categoryName: '', // 类目名称
  status: 1, // 上架状态
  titleType: null, // 标题类型
  removeTitle: '', // 删除关键词
  suffixTitle: '', // 标题后缀
  prefixTitle: '', // 标题前缀
  replaceTitle: [['', '']],  // 关键词替换列表
  mainImageRemove: '', // 删除商品主图第几张
  behindImageRemove: '', // 删除商品详情图后几张
  frontImageRemove: '',  // 删除商品详情图前几张
  priceType: 1, // SKU 价格类型
  priceProportion: 0, // 修正比例
  priceRepair: 0, // 修正值
  price: 0, // 直接设置价格
  stockDeductionType: null, // 减库存方式
  stockType: 0, // 库存类型
  priceFormatType: 1, // 价格处理
  purchaseLimitOnce: '', // 每次限购
  purchaseLimitUser: '', // 累计限购
  returnPolicy: '', // 服务与资质
  defaultTemplate: '0'
});

const reviewTemplate = () => {
  api.getTemplateInfo(tpId.value).then(res => {
    if (res.data) {
      res.data.replaceTitle = res.data.replaceTitle.split(';').map(v => {
        return v.split(':')
      })
      Object.assign(formState, res.data)
    }
  })
}

const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 9 },
};

const addTitleRex = () => {
  formState.replaceTitle.push(['', ''])
}

const delTitleRex = (id) => {
  formState.replaceTitle.splice(id, 1)
}

const changeSelect = (val) => {
  const item = category_list.value.find(v => v.cid == val)
  formState.categoryName = item.name
}

const changeReturnPolicy = (val) => {
}

const rules = {
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'change' },
  ],
  categoryId: [
    { required: true, message: '请选择类目id', trigger: 'change' },
  ],
  titleType: [
    { required: true, message: '请选择商品标题格式', trigger: 'change' },
  ],
  status: [
    { required: true, message: '请选择上架状态', trigger: 'change' },
  ],
  priceType: [
    { required: true, message: '请选择SKU价格模式', trigger: 'change' },
  ],
  stockDeductionType: [
    { required: true, message: '请选择减库存方式', trigger: 'change' },
  ],
  stockType: [
    { required: true, message: '请选择库存方式', trigger: 'change' },
  ],
  priceFormatType: [
    { required: true, message: '请选择价格处理方式', trigger: 'change' },
  ],
  returnPolicy: [
    { required: true, message: '请填写售后服务', trigger: 'change' },
  ]
}

const submit = () => {
  formRef.value.validateFields().then(res => {
    let params = _.cloneDeep(formState)
    params.replaceTitle = params.replaceTitle.map(v => {
      return v.join(":")
    }).join(";")
    console.log(params)
    params.replaceTitle = params.replaceTitle == ':' ? '' : params.replaceTitle
    if (!params.id) delete params.id
    let fun = null
    if (params.id) {
      fun = api.updateTemplate
    } else {
      fun = api.addTemplate
    }
    fun(params).then(res => {
      if (res.code == 200) {
        message.success(`${params.id ? '修改' : '保存'}模板成功`)
        onClose()
      }
    })
  }).catch(() => {
    console.log(formState)
  })
}

watch(() => isOpen.value, (v) => {
  if (v) {
    initForm()
    if (tpId.value) {
      reviewTemplate()
    }
  }
})

const initForm = () => {
  Object.assign(formState, {
    id: null,
    templateName: "", // 模板名称
    categoryId: null, // 类目id
    categoryName: '', // 类目名称
    status: 1, // 上架状态
    titleType: null, // 标题类型
    removeTitle: '', // 删除关键词
    suffixTitle: '', // 标题后缀
    prefixTitle: '', // 标题前缀
    replaceTitle: [['', '']],  // 关键词替换列表
    mainImageRemove: '', // 删除商品主图第几张
    behindImageRemove: '', // 删除商品详情图后几张
    frontImageRemove: '',  // 删除商品详情图前几张
    priceType: 1, // SKU 价格类型
    priceProportion: 0, // 修正比例
    priceRepair: 0, // 修正值
    price: 0, // 直接设置价格
    stockDeductionType: null, // 减库存方式
    stockType: 0, // 库存类型
    priceFormatType: 1, // 价格处理
    purchaseLimitOnce: '', // 每次限购
    purchaseLimitUser: '', // 累计限购
    returnPolicy: '', // 服务与资质
    defaultTemplate: '0'
  })
}
</script>

<template>
  <a-drawer width="100%" title="新增模板" placement="right" :open="isOpen" @close="onClose"
    :footer-style="{ textAlign: 'right' }" :get-container="false" :destroyOnClose="true" :maskClosable="false">
    <a-form ref="formRef" name="custom-validation" :model="formState" v-bind="layout" :rules="rules" v-if="isOpen">
      <a-page-header class="border-b border-b-solid border-b-[#EBEDF0] mb-24px" title="基础信息" />
      <!-- 基础信息 -->
      <a-form-item has-feedback label="复制模板名称" name="templateName">
        <a-input class="w-220px" v-model:value="formState.templateName" placeholder="系统默认模板" />
      </a-form-item>
      <a-form-item has-feedback label="商品类目" name="categoryId">
        <a-select class="!w-220px" ref="select" v-model:value="formState.categoryId" @change="changeSelect">
          <template v-for="item in category_list">
            <a-select-option :value="item.cid" v-if="item.cid != 0">{{ item.name }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item has-feedback label="商品标题" name="titleType">
        <a-radio-group class="my-4.5px" v-model:value="formState.titleType" :options="titleOption" />
        <span class="color-[#999] ml-5px">标题长度超过30个字时将自动去除超出部分</span>
        <div v-if="formState.titleType == 1">
          <a-form-item has-feedback label="增加前后缀" class="mt-10px">
            <a-form-item-rest>
              <a-flex align="center" justify="flex-start">
                <a-col :span="10">
                  <a-input v-model:value="formState.prefixTitle" placeholder="请输入前缀词" />
                </a-col>
                <a-col :span="4" class="text-center">原标题</a-col>
                <a-col :span="10">
                  <a-input v-model:value="formState.suffixTitle" placeholder="请输入后缀词" />
                </a-col>
              </a-flex>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item has-feedback label="修改关键词" v-for="(item, idx) of formState.replaceTitle" :key="idx"
            class="mt-10px">
            <a-form-item-rest>
              <a-flex align="center" justify="flex-start">
                <a-col :span="10">
                  <a-input v-model:value="item[0]" placeholder="请输入前缀词" />
                </a-col>
                <a-col :span="4" class="text-center">原标题</a-col>
                <a-col :span="10">
                  <a-input v-model:value="item[1]" placeholder="请输入后缀词" />
                </a-col>
                <a-col :span="3" class="text-center" v-if="idx == formState.replaceTitle.length - 1">
                  <a-button @click="addTitleRex" type="link">添加</a-button>
                </a-col>
                <a-col :span="3" class="text-center" v-if="idx < formState.replaceTitle.length - 1">
                  <a-button @click="delTitleRex(idx)" type="link" danger>删除</a-button>
                </a-col>
              </a-flex>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item has-feedback label="删除关键词" name="checkPass">
            <a-form-item-rest>
              <a-input v-model:value="formState.removeTitle" placeholder="多个关键词请用;区分" />
            </a-form-item-rest>
          </a-form-item>
        </div>
      </a-form-item>
      <a-form-item has-feedback label="上架状态" name="status">
        <a-radio-group v-model:value="formState.status" :options="availableOption" />
      </a-form-item>
      <a-page-header class="border-b border-b-solid border-b-[#EBEDF0] mb-24px" title="图片信息" />
      <!-- 图片信息 -->
      <a-form-item has-feedback label="商品主图" name="checkPass">
        <a-flex align="center" justify="flex-start">
          <span>删除原商品主图第</span>
          <a-col :span="8" class="mx-10px">
            <a-input v-model:value="formState.mainImageRemove" placeholder="请输入后缀词" />
          </a-col>
          <span>张</span>
          <span class="color-[#999] ml-5px">便于去除原图水印等信息</span>
        </a-flex>
      </a-form-item>
      <a-form-item has-feedback label="商品详情图" name="checkPass">
        <a-form-item-rest>
          <a-flex align="center" justify="flex-start">
            <span>删除原商品详情图前第</span>
            <a-col :span="8" class="mx-10px">
              <a-input v-model:value="formState.frontImageRemove" placeholder="请输入后缀词" />
            </a-col>
            <span>张</span>
          </a-flex>
          <a-flex align="center" justify="flex-start" class="mt-16px">
            <span>删除原商品详情图后第</span>
            <a-col :span="8" class="mx-10px">
              <a-input v-model:value="formState.behindImageRemove" placeholder="请输入后缀词" />
            </a-col>
            <span>张</span>
          </a-flex>
        </a-form-item-rest>
      </a-form-item>
      <a-page-header class="border-b border-b-solid border-b-[#EBEDF0] mb-24px" title="销售信息" />
      <!-- 销售信息 -->
      <a-form-item has-feedback label="SUK价格" name="priceType">
        <a-radio-group v-model:value="formState.priceType" :options="SKUOption" class="pt-4px" />
        <a-form-item-rest>
          <a-form-item has-feedback>
            <a-flex align="center" justify="flex-start" class="mt-16px" v-if="formState.priceType == 1">
              <span>商品结算价 x</span>
              <a-col :span="5" class="ml-10px">
                <a-input-number :controls="false" :min="0" :max="100" addon-after="%"
                  v-model:value="formState.priceProportion" />
              </a-col>
              <a-col :span="2" class="text-center">后，</a-col>
              <a-col :span="7">
                <a-input-number :controls="false" :min="0" addon-before="减" addon-after="元"
                  v-model:value="formState.priceRepair" />
              </a-col>
            </a-flex>
            <a-flex align="center" justify="flex-start" class="mt-16px" v-if="formState.priceType == 0">
              <span class="mr-6px">统一设置价格为</span>
              <a-col :span="7">
                <a-input-number :controls="false" :min="0" addon-after="元" v-model:value="formState.price" />
              </a-col>
            </a-flex>
          </a-form-item>
        </a-form-item-rest>
      </a-form-item>
      <a-form-item has-feedback label="SUK库存" name="stockType">
        <a-radio-group v-model:value="formState.stockType" :options="stockOption" />
      </a-form-item>
      <a-form-item has-feedback label="减库存方式" name="stockDeductionType">
        <a-radio-group v-model:value="formState.stockDeductionType" :options="cutOption" />
      </a-form-item>
      <a-form-item has-feedback label="价格处理" name="priceFormatType">
        <a-radio-group v-model:value="formState.priceFormatType" :options="priceOption" />
      </a-form-item>
      <a-form-item has-feedback label="商品限购" name="purchase" class="pt-16px">
        <a-form-item-rest>
          <a-flex align="center" justify="flex-start">
            <a-col :span="9" class="mr-16px relative">
              <span class="absolute top--20px left-5px color-gray">单用户累计限购</span>
              <a-input-number :controls="false" :min="0" addon-after="件" placeholder="单用户累计限购"
                v-model:value="formState.purchaseLimitUser" />
            </a-col>
            <a-col :span="9" class="relative">
              <span class="absolute top--20px left-5px color-gray">每次限购</span>
              <a-input-number :controls="false" :min="0" addon-after="件" placeholder="每次限购"
                v-model:value="formState.purchaseLimitOnce" />
            </a-col>
          </a-flex>
        </a-form-item-rest>
      </a-form-item>
      <a-page-header class="border-b border-b-solid border-b-[#EBEDF0] mb-24px" title="服务与资质" />
      <a-form-item has-feedback label="售后服务" name="returnPolicy">
        <!-- <a-input v-model:value="formState.returnPolicy" placeholder="请输入服务与资质" /> -->
        <a-select class="!w-220px" ref="select" v-model:value="formState.returnPolicy" @change="changeReturnPolicy">
          <a-select-option v-for="item in returnPolicy_list" :value="item.cid">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="submit">{{ formState.id ? '修改' : '保存' }}模板</a-button>
    </template>
  </a-drawer>
</template>

<style></style>
